package cn.hyxy.hadoop;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**原始数据：
 *  Jack Mary
	Jack Jack
	Mike
	Json Rose
	Rose Rose
	Json
	
	执行完Mapper之后：
 * 		Jack,[1,1,1]
		Json,[1,1]
		Mary,[1]
		Mike,[1]
		Rose,[1,1,1]
		
	执行完reduce(),即运行完此程序之后：
		Jack	3
		Json	2
		Mary	1
		Mike	1
		Rose	3
*
 */


public class Demo02_WordCountMR extends Configured implements Tool {
	@Override
	public int run(String[] args) throws Exception {
		if(args.length!=2) {
			System.out.println("usage ...");
			return -1;
		}
		Configuration config = getConf();
		FileSystem fs = FileSystem.get(config);
		Path path = new Path(args[1]);
		if(fs.exists(path)) {
			fs.delete(path, true);
		}
		Job job = Job.getInstance(config, "字符统计");		
		job.setJarByClass(getClass());
		job.setMapperClass(MyMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(LongWritable.class);
		job.setReducerClass(Reducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setNumReduceTasks(2);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, path);
		boolean boo = job.waitForCompletion(true);
		return boo ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int code = ToolRunner.run(new Demo02_WordCountMR(), args);
		System.exit(code);
	}

	public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
		@Override
		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String str = value.toString();
			String[] strs = str.split("\\s+");// 空格，制表符号
			for (String s : strs) {
				context.write(new Text(s), new LongWritable(1));
			}
		}
	}
	public static class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
		@Override
		protected void reduce(Text key3, Iterable<LongWritable> value3,
				Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
			long sum = 0;
			for (LongWritable ii : value3) {
				sum = sum + ii.get();
			}
			context.write(key3, new LongWritable(sum));
		}
	}

}
